package org.youyun56.gpsserver.common;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;
import org.youyun56.gpsserver.entity.Car;

public class SessionManager {

    /**
     * 
     */
    public final static ConcurrentHashMap<Integer, ConcurrentHashMap<String, IoSession>> pool = new ConcurrentHashMap<Integer, ConcurrentHashMap<String, IoSession>>();
    public final static Logger logger = Logger.getLogger(SessionManager.class);

    public static void brocast(Integer cityId, String message) {
        Collection<IoSession> sessions = pool.get(cityId).values();
        if (CollectionUtil.isNotEmpty(sessions)) {
            for (IoSession ioSession : sessions) {
                ioSession.write(message);
            }
        }
    }

    public static void changeCity(Integer cityId, IoSession session) {
        Car car = (Car) session.getAttribute(SessionKey.CAR);
        if (car != null) {
            if (car.getFocusCity() != null && car.getFocusCity() != cityId) {
                ConcurrentHashMap<String, IoSession> sessions = pool.get(car.getFocusCity());
                sessions.remove(car.getCarMobile());
                pool.get(cityId).put(car.getCarMobile(), session);
                car.setFocusCity(cityId);
            }
        }
    }

    public static void addSession(Integer cityId, IoSession session, String mobile) {
        ConcurrentHashMap<String, IoSession> sessions = pool.get(cityId);
        sessions.put(mobile, session);
    }

    public static IoSession getSession(Integer cityId, String mobile) {
        ConcurrentHashMap<String, IoSession> sessions = pool.get(cityId);
        return sessions.get(mobile);
    }

    public static void removeSession(IoSession session) {
        Car car = (Car) session.getAttribute(SessionKey.CAR);
        if (car != null) {
            pool.get(car.getFocusCity()).remove(car.getCarMobile());
            session.removeAttribute(SessionKey.CAR);
        }
    }
}
